package com.snail.controller;

import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.snail.model.dto.SearchResultDTO;
import com.snail.model.entity.Product;
import com.snail.model.pojo.Result;
import com.snail.model.pojo.SearchHitResult;
import com.snail.service.BizSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RequestMapping("/searchAll")
@RestController
public class BizSearchController {
    @Autowired
    BizSearchService bizSearchService;


    @GetMapping("/query")
    public ResponseEntity<List<SearchResultDTO>> searchAll(@RequestParam String keyword) {
        try {
            return ResponseEntity.ok(bizSearchService.searchAll(keyword));
        } catch (Exception e) {
            e.printStackTrace(); // 可以加日志
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/products")
    public ResponseEntity<?> searchProductByName(@RequestParam String keyword) {
        System.out.println("搜索结果："+bizSearchService.searchProduct(keyword,1,10));
        SearchResponse<Product> response = bizSearchService.searchProduct(keyword, 1, 10);

        // 转换成 List<Product>
        List<Product> products = response.hits().hits()
                .stream()
                .map(hit -> hit.source())  // 获取文档对象
                .filter(Objects::nonNull)
                .toList();
        return ResponseEntity.ok(products);
    }
}
